//
//  MTMineClubViewController.swift
//  MT
//
//  Created by ooops on 2019/12/28.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import JXPagingView
import JXCategoryView
import YPNavigationBarTransition
import JXSegmentedView
import JMessage

class MTMineClubViewController: BaseViewController {
    
    var message: JMSGMessage?
    var fromUser: JMSGUser?
    var datas: [JMSGConversation] = []
    var groupList: [JMSGGroup] = []
    private var chatRoomConversation: JMSGConversation?
    fileprivate var badgeCount = 0
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    private lazy var defaultImage: UIImage? = UIImage(named: defaultPlaceholderIcon60x60)
    fileprivate var selectGroup: JMSGGroup!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if isConnecting {
            titleTips.text = "连接中"
            titleTipsView.isHidden = false
        } else {
            titleTipsView.isHidden = true
        }
        _getConversations()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        titleTipsView.isHidden = true
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        //NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kUpdateConversation), object: nil)
        JMessage.remove(self, with: nil)
    }
    
    fileprivate var isConnecting = false
    fileprivate var showNetworkTips = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的俱乐部"
        JMessage.add(self, with: self.chatRoomConversation)
        view.backgroundColor = UIColor.theme.background
        view.addSubview(friendRequestView)
        view.addSubview(chatRoomView)
        view.addSubview(tableView)
        
        friendRequestView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight)
            make.height.equalTo(64)
        }
        
        chatRoomView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(friendRequestView.snp.bottom)
            make.height.equalTo(64)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(chatRoomView.snp.bottom)
        }
        
        getChatRoomMessage()
        
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: NSNotification.Name(rawValue: "kNetworkReachabilityChangedNotification"), object: nil)

        _getConversations()
        NotificationCenter.default.addObserver(self, selector: #selector(_getConversations), name: NSNotification.Name(rawValue: kUpdateConversation), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connectClose), name: NSNotification.Name.jmsgNetworkDidClose, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connectSucceed), name: NSNotification.Name.jmsgNetworkDidLogin, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(connecting), name: NSNotification.Name.jmsgNetworkIsConnecting, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(_updateBadge), name: NSNotification.Name(rawValue: kUpdateVerification), object: nil)
    }
    
    @objc private func _updateBadge() {
        JCVerificationInfoDB.shareInstance.quaryRequestCountData(verType: MTRequestVerifyType.group.rawValue) {[weak self] (count) in
            guard let weakSelf = self else { return }
            weakSelf.friendRequestView.setRedPoint(pointValue: count)
            weakSelf.filterNotFriendConversation(pointValue: count)
        }
    }
    
    /// 过滤非好友聊天会话消息 - 俱乐部 / 好友聊天
    private func filterNotFriendConversation(pointValue: Int) {
        let conversations = self.datas.filter { (conversation) -> Bool in
            /// 过滤好友关系会话
            if let _ = conversation.target as? JMSGUser {
                return false
            }
            /// 过滤聚会任务群 会话
            if let target: JMSGGroup = conversation.target as? JMSGGroup, let desc = target.desc, desc.contains("|.>p_t_g<.|") {
                return false
            }
            return true
        }
        
        var count = conversations.unreadCount
        if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
            let badgeCount = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
            count += badgeCount
        }
        
        if count > 99 {
            navigationVC?.tabBarItem.badgeValue = "99+"
        } else {
            navigationVC?.tabBarItem.badgeValue = count + pointValue == 0 ? nil : "\(count + pointValue)"
        }
    }
    
    @objc func reachabilityChanged(note: NSNotification) {
        if let curReach = note.object as? Reachability {
            let status = curReach.currentReachabilityStatus()
            switch status {
            case NotReachable:
                notReachable()
            default :
                reachable()
            }
        }
    }
    
    @objc func _getConversations() {
        JMSGConversation.allConversations { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            guard let conversatios = result else {
                return
            }
            
            /// 过滤好友聊天, 返回的会话对象不包括聊天室
            /// 会话消息只有三种 单聊 / 群聊(俱乐部) / 聊天室(广场)
            /// 又因为不加入俱乐部, 无法聊天, 所以回去的所有会话列表就是, 我的俱乐部
            weakSelf.datas = (conversatios as! [JMSGConversation]).filter({ (conversation) -> Bool in
                return conversation.conversationType == .group
            })
            
            weakSelf.datas = weakSelf.sortConverstaions(weakSelf.datas)
            weakSelf.filterNotFriendConversation()
            weakSelf._updateBadge()
            weakSelf.tableView.reloadData()
        }
    }
    
    /// 过滤聚会任务群
    private func filterNotFriendConversation() {
        self.datas = self.datas.filter { (conversation) -> Bool in
            /// 过滤聚会任务群 如果群组描述中包含 "|.>p_t_g<.|" 则为聚会任务群
            if let target: JMSGGroup = conversation.target as? JMSGGroup, let desc = target.desc, desc.contains("|.>p_t_g<.|") {
                return false
            }
            return true
        }
    }

    fileprivate func sortConverstaions(_ convs: [JMSGConversation]) -> [JMSGConversation] {
        var stickyConvs: [JMSGConversation] = []
        var allConvs: [JMSGConversation] = []
        for index in 0..<convs.count {
            let conv = convs[index]
            if conv.ex.isSticky {
                stickyConvs.append(conv)
            } else {
                allConvs.append(conv)
            }
        }

        stickyConvs = stickyConvs.sorted(by: { (c1, c2) -> Bool in
            c1.ex.stickyTime > c2.ex.stickyTime
        })

        allConvs.insert(contentsOf: stickyConvs, at: 0)
        return allConvs
    }
    
    fileprivate lazy var titleTips: UILabel = {
        var tips = UILabel(frame: CGRect(x: 23, y: 0, width: 67, height: 44))
        tips.font = UIFont.systemFont(ofSize: 18)
        tips.textColor = UIColor.white
        tips.textAlignment = .left
        tips.backgroundColor = UIColor(hex: 0x5AD4D3)
        return tips
    }()

    fileprivate lazy var titleTipsView: UIView = {
        var view = UIView(frame: CGRect(x: self.view.width / 2 - 45, y: 20, width: 90, height: 44))
        view.backgroundColor =  UIColor(hex: 0x5AD4D3)
        let activityView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 12, width: 20, height: 20))
        view.addSubview(activityView)
        activityView.startAnimating()
        view.addSubview(self.titleTips)
        view.isHidden = true
        return view
    }()
    
    lazy var friendRequestView: MTDiscoverFriendRequestView = {
        let r: MTDiscoverFriendRequestView = MTDiscoverFriendRequestView(title: "待处理请求", subTitle: "俱乐部验证消息", type: .group)
        r.backgroundColor = UIColor(hex: 0xf6f6f6)
        r.delegate = self
        return r
    }()
    
    lazy var chatRoomView: MTChatRoomLSingleView = {
        let l = MTChatRoomLSingleView()
        //l.backgroundColor = UIColor(hex: 0xf6f6f6)
        l.delegate = self
        return l
    }()
    
    fileprivate lazy var errorTips: JCNetworkTipsCell = JCNetworkTipsCell()

    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(JCConversationCell.self, forCellReuseIdentifier: "JCConversationCell")
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.backgroundColor = UIColor.theme.background
        table.showsVerticalScrollIndicator = false
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
        table.emptySetView = ViewFactory.emptySetView()
        return table
    }()
    
    /// 极光的API没有提供获取聊天室最后一条消息的方法, 只能自己搞
    private func getChatRoomMessage() {
        chatRoomView.lastMessage = nil
        if let roomId = UserCenter.default.roomId {
            JMSGChatRoom.leaveChatRoom(withRoomId: "\(roomId)") { (result, error) in
                JMSGChatRoom.enterChatRoom(withRoomId: "\(roomId)") {[weak self] (result, error) in
                    guard let weakSelf = self else { return }
                    if error != nil {
                        DispatchQueue.main.async {
                            weakSelf.chatRoomView.snp.updateConstraints { (make) in
                                make.height.equalTo(0)
                            }
                        }
                        return
                    }
                    MBProgressHUD_JChat.hide(forView: weakSelf.view, animated: true)
                    if let con1 = result as? JMSGConversation {
                        weakSelf.chatRoomConversation = con1
                        DispatchQueue.main.async {
                            weakSelf.chatRoomView.snp.updateConstraints { (make) in
                                make.height.equalTo(64)
                            }
                        }
                    } else {
                        printLog("\(String(describing: error))")
                        if let error = error as NSError? {
                            if error.code == 851003 {//member has in the chatroom
                                JMSGConversation.createChatRoomConversation(withRoomId: "\(roomId)") { (result, error) in
                                    weakSelf.chatHistoryMessage(result: result, error: error)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    private func chatHistoryMessage(result: Any?, error: Error?) {
        if error != nil {
            DispatchQueue.main.async {
                self.chatRoomView.snp.updateConstraints { (make) in
                    make.height.equalTo(0)
                }
            }
            return
        }
        if let con = result as? JMSGConversation {
            DispatchQueue.main.async {
                self.chatRoomView.snp.updateConstraints { (make) in
                    make.height.equalTo(64)
                }
            }
        }
    }
    
    func _getChatRoomList(complete: @escaping ([JMSGChatRoom]?) -> Void ) {
        JMSGChatRoom.getListWithAppKey(nil, start: 0, count: 1) { (result, error) in
            if error != nil {
                complete(nil)
                return
            }
            DispatchQueue.main.async {
                if let rooms = result as? [JMSGChatRoom] {
                    complete(rooms)
                } else {
                    complete(nil)
                }
            }
        }
    }
    
    /// 进入聊天室
    @objc func enterChatRoom() {
        //navigationController?.pushViewController(JCChatRoomListViewController(), animated: true)
        
        let roomId = "\(UserDefaults.MTUserCenter.roomId.storedInt)"
        
        _getChatRoomList { [weak self]  (rooms) in
            guard let weakSelf = self else { return }
            if let room = rooms?.first {
                MBProgressHUD_JChat.show(text: "正在进入广场", view: weakSelf.view)
                JMSGChatRoom.leaveChatRoom(withRoomId: roomId) {(result, error) in
                    printLog("leave the chat room，error:\(String(describing: error))")
                    let con = JMSGConversation.chatRoomConversation(withRoomId: roomId)
                    if con == nil {
                        printLog("enter the chat room first")
                        JMSGChatRoom.enterChatRoom(withRoomId: roomId) { (result, error) in
                            MBProgressHUD_JChat.hide(forView: weakSelf.view, animated: true)
                            if let con1 = result as? JMSGConversation {
                                let vc = JCChatRoomChatViewController(conversation: con1, room: room)
                                weakSelf.navigationVC?.pushViewController(vc, animated: true)
                            } else {
                                printLog("\(String(describing: error))")
                                if let error = error as NSError? {
                                    if error.code == 851003 {//member has in the chatroom
                                        JMSGConversation.createChatRoomConversation(withRoomId: roomId) { (result, error) in
                                            if let con = result as? JMSGConversation {
                                                let vc = JCChatRoomChatViewController(conversation: con, room: room)
                                                weakSelf.navigationVC?.pushViewController(vc, animated: true)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        printLog("go straight to the chat room session")
                        let vc = JCChatRoomChatViewController(conversation: con!, room: room)
                        weakSelf.navigationVC?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
}

extension MTMineClubViewController: MTDiscoverFriendRequestViewDelegate {
    
    func didTapFriendRequestEntrance() {
        self.navigationVC?.pushViewController(MTFriendViewRequestVerifyController(friendRequestType: .group), animated: true)
        self.friendRequestView.setRedPoint(pointValue: 0)
        JCVerificationInfoDB.shareInstance.updateAllUnReadRequestMessage(verType: MTRequestVerifyType.group.rawValue)
    }
    
}


extension MTMineClubViewController: UITableViewDataSource, UITableViewDelegate {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return showNetworkTips ? datas.count + 1 : datas.count
        }
        
        public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if showNetworkTips && indexPath.row == 0 {
                errorTips.selectionStyle = .none
                return errorTips
            }
            return tableView.dequeueReusableCell(withIdentifier: "JCConversationCell", for: indexPath)
        }
        
        public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            guard let cell = cell as? JCConversationCell else {
                return
            }
            cell.bindConversation(datas[showNetworkTips ? indexPath.row - 1 : indexPath.row])
        }
        
        public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            if showNetworkTips && indexPath.row == 0 {
                return 40
            }
            return 64
        }
        
        public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
            if showNetworkTips && indexPath.row == 0 {
                return
            }
            let conversation = datas[showNetworkTips ? indexPath.row - 1 : indexPath.row]
            conversation.clearUnreadCount()
            guard let cell = tableView.cellForRow(at: indexPath) as? JCConversationCell else {
                return
            }
            cell.bindConversation(conversation)
            let vc = JCChatViewController(conversation: conversation)
            navigationVC?.pushViewController(vc, animated: true)
        }
        
        func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
            return .delete
        }
        
        func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            return true
        }
        
        func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
            return false
        }
        
        func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let deleteAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
                completionHandler(true)
                self._delete(indexPath)
            }
            deleteAction.image = UIImage(named: "icon_trash")
            deleteAction.backgroundColor = UIColor(hex: 0xFFC000)
            
            
            let conversation = datas[showNetworkTips ? indexPath.row - 1 : indexPath.row]
            
            let upAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
                completionHandler(true)
                conversation.ex.isSticky = !conversation.ex.isSticky
                self._getConversations()
            }
            //upAction.image = UIImage(named: "icon_trash")
            if conversation.ex.isSticky {
                upAction.title = "取消置顶"
            } else {
                upAction.title = "置顶"
            }
            upAction.backgroundColor = UIColor(hex: 0xFFC000)
            
            
            let actions:[UIContextualAction] = [upAction, deleteAction]
            let action:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)
            action.performsFirstActionWithFullSwipe = false
            return action
        }
        
        private func _delete(_ indexPath: IndexPath) {
            let conversation = datas[indexPath.row]
            let tager = conversation.target
            JCDraft.update(text: nil, conversation: conversation)
            if conversation.ex.isGroup {
                guard let group = tager as? JMSGGroup else {
                    return
                }
                JMSGConversation.deleteGroupConversation(withGroupId: group.gid)
            } else {
                guard let user = tager as? JMSGUser else {
                    return
                }
                JMSGConversation.deleteSingleConversation(withUsername: user.username, appKey: user.appKey!)
            }
            datas.remove(at: indexPath.row)
    //        if datas.count == 0 {
    //            emptyView.isHidden = false
    //        } else {
    //            emptyView.isHidden = true
    //        }
            tableView.reloadData()
        }
    
}

extension MTMineClubViewController: JMessageDelegate {
    
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        _getConversations()
    }
    
    func onConversationChanged(_ conversation: JMSGConversation!) {
        _getConversations()
    }
    
    func onGroupInfoChanged(_ group: JMSGGroup!) {
        _getConversations()
    }
    
    func onSyncRoamingMessageConversation(_ conversation: JMSGConversation!) {
        _getConversations()
    }
    
    func onSyncOfflineMessageConversation(_ conversation: JMSGConversation!, offlineMessages: [JMSGMessage]!) {
        _getConversations()
    }
    
    func onReceive(_ retractEvent: JMSGMessageRetractEvent!) {
        _getConversations()
    }
    
    func onReceiveChatRoomConversation(_ conversation: JMSGConversation!, messages: [JMSGMessage]!) {
        printLog("message: \(String(describing: messages))")
        self.chatRoomView.lastMessage = messages?.last
        self.chatRoomView.conversation = conversation
    }
    
}

// MARK: - network tips
extension MTMineClubViewController {
    
    func reachable() {
        if !showNetworkTips {
            return
        }
        showNetworkTips = false
        tableView.reloadData()
    }
    
    func notReachable() {
        if showNetworkTips {
            return
        }
        showNetworkTips = true
        if datas.count > 0 {
            let indexPath = IndexPath(row: 0, section: 0)
            tableView.beginUpdates()
            tableView.insertRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()
        } else {
            tableView.reloadData()
        }
    }
    
    @objc func connectClose() {
        isConnecting = false
        DispatchQueue.main.async {
            self.titleTipsView.isHidden = true
        }
    }
    
    @objc func connectSucceed() {
        isConnecting = false
        DispatchQueue.main.async {
            self.titleTipsView.isHidden = true
        }
    }
    
    @objc func connecting() {
        _connectingSate()
    }
    
    func _connectingSate() {
        let window = UIApplication.shared.delegate?.window
        if let window = window {
            guard let rootViewController = window?.rootViewController as? JCMainTabBarController else {
                return
            }
            guard let nav = rootViewController.selectedViewController as? BaseNavController else {
                return
            }
            guard let currentVC = nav.topViewController else {
                return
            }
            if currentVC.isKind(of: JCConversationListViewController.self) {
                isConnecting = true
                titleTips.text = "连接中"
                titleTipsView.isHidden = false
            }
        }
    }
}

extension MTMineClubViewController: MTChatRoomLSingleViewDelegate {
    func didTapEntranceChatRoom() {
        enterChatRoom()
    }
}


extension MTMineClubViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return UIScrollView()
    }
}


//extension MTMineClubViewController {
//    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
//        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
//    }
//}
